#!/user/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
import sys

import promconv
from aiohttp import web
from loginfo import Logger

logger = Logger()
sys.stdout.reconfigure(encoding='utf-8')

'''
异步函数webhook来处理Webhook请求
'''
async def webhook(request):
    try:
        logger.loginfo("- - - " * 10)
        logger.loginfo("webhook-conv-received")
        url = str(request.url)  # 获取请求的URL
        data = await request.json()  # 异步获取请求的JSON数据
        query_params = request.query  # 获取查询参数
        key_value = query_params.get('key', '')  # 获取名为 'a' 的查询参数的值
        # 在这里处理接收到的数据
        logger.loginfo("rec-body: url='" + url + "'")
        logger.loginfo("rec-body: data='" + str(data) + "'")
        logger.loginfo("rec-body: params='" + str(key_value) + "'")
        # 在这里处理 webhook 转发服务
        promconv.conv(key_value, data)
        # end
        return web.Response(text='OK')
    except Exception as e:
        # 捕捉异常，并进行相应的处理
        print("Exception:", str(e))
        logger.loginfo("webhook-conv-received-error: " + str(e) + "")
        return web.Response(text='Error', status=500)


'''
运行aiohttp应用
'''
app = web.Application()
app.router.add_post('/webhook', webhook)

if __name__ == '__main__':
    logger.loginfo("PromAlert Conversion Services - Run")
    web.run_app(app, host='0.0.0.0', port=15000)
